<template>
  <div>
    <el-button type="primary" @click="dialogFormVisible = true"
      >添加用户</el-button
    >
    <el-table :data="userList" stripe style="width: 100%,height:100px">
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="role_name" label="职位"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="email" label="email"> </el-table-column>
      <el-table-column label="操作" prop="mg_state">
        <template slot-scope="scope">
          <el-switch
            @change="changeState(scope.row)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="状态" prop="mg_state">
        <template slot-scope="scope">
          <!-- 修改用户信息 -->
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            circle
            @click="showEditUser(scope.row)"
          ></el-button>
          <!-- 删除用户 -->
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            circle
            @click="deleteUser(scope.row)"
          ></el-button>
          <el-button
            type="info"
            size="mini"
            icon="el-icon-message"
            circle
            @click="showRoles(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[3, 5, 15, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
      <el-form :model="addUserData">
        <el-form-item label="用户名">
          <el-input
            v-model="addUserData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="addUserData.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="addUserData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="addUserData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改用户" :visible.sync="dialogFormUser">
      <el-form :model="userEditData">
        <el-form-item label="用户名">
          <el-input
            v-model="userEditData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userEditData.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userEditData.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormUser = false">取 消</el-button>
        <el-button type="primary" @click="editPutUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="用户角色" :visible.sync="dialogFormRoles">
      <el-form :model="userRolesData">
        <el-form-item label="用户名">
          <el-input
            v-model="userRolesData.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <!-- 展示用户角色 -->
        <el-select v-model="roleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormRoles = false">取 消</el-button>
        <el-button type="primary" @click="editPutRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      userList: [],
      total: 0,
      pageSize: 3,
      dialogFormVisible: false,
      addUserData: {
        username: "",
        password: "",
        mobile: "",
        email: "",
      },
      dialogFormUser: false,
      userEditData: {},
      dialogFormRoles: false,
      userRolesData: {},
      roleList: [],
      roleId: "",
      // role_name: "",
    };
  },
  methods: {
    //获取前用户数据列表
    async getusers(pagenum = 1, pagesize = 3) {
      var { data } = await this.$axios.get(
        `/users?pagenum=${pagenum}&pagesize=${pagesize}`
      );
      if (data.meta.status == 200) {
        console.log(data);
        this.userList = data.data.users;
        this.total = data.data.total;
      } else {
        this.$message.error(data.meta.msg);
      }
    },
    //设置用户列表每夜的条数
    async handleSizeChange(pagesize) {
      this.getusers(1, pagesize);
    },
    //设置跳转到第几页
    handleCurrentChange(pagenum) {
      this.getusers(pagenum, this.pageSize);
    },
    //postUsert添加用户
    async postUser() {
      var { data } = await this.$axios.post("/users", this.addUserData);
      if (data.meta.status == 201) {
        this.$message({
          message: data.meta.msg,
          type: "success",
        });
        this.dialogFormVisible = false;
        this.getusers(1, this.pagesize);
        this.addUserData = {};
      } else {
        this.$message.error(data.meta.msg);
      }
    },
    //修改用户状态
    async changeState(rows) {
      // console.log(1321);
      //新状态
      // console.log(rows);
      //发送ajax请求
      var { data } = await this.$axios.put(
        `/users/${rows.id}/state/${rows.mg_state}`
      );
      // console.log(data);
      //请求成功
      if (data.meta.status == 200) {
        //成功弹窗
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
      } else {
        //如果信息错误，则不发生修改  mg_state去反
        mg_state = !mg_state;
        this.$message({
          type: "error",
          message: data.meta.msg,
        });
      }
    },
    //修改用户信息
    showEditUser(userinfo) {
      this.userEditData = userinfo;
      this.dialogFormUser = true;
    },
    ///修改用户信息
    async editPutUser() {
      var { data } = await this.$axios.put(
        `users/` + this.userEditData.id,
        this.userEditData
      );
      console.log(data);
      //关闭弹窗
      this.dialogFormUser = false;
      if (data.meta.status == 200) {
        //弹出提醒
        this.$message({
          type: "success",
          message: data.meta.msg,
        });
      } else {
        this.$message({
          type: "error",
          message: data.meta.msg,
        });
        //==============================完成作业=======================================
        //取消之后重新渲染数据
        this.getusers()
      }
    },
    //删除
    deleteUser(userinfo) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          //发送删除请求
          var { data } = await this.$axios.delete(`/users/` + userinfo.id);
          console.log(data);
          if (data.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //=================================
            //作业：解决删除成功后数据加载问题
            this.getusers();
          } else {
            this.$message({
              type: "error",
              message: data.meat.msg,
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //分配用户角色
    async showRoles(userinfo) {
      this.role_name = userinfo.role_name;
      this.userRolesData = userinfo;

      this.dialogFormRoles = true;
      //获取所有角色信息
      var { data } = await this.$axios.get("roles");
      // console.log(data);
      this.roleList = data.data;
    },
    //修改角色信息
    async editPutRole() {
      // this.userRolesData.id
      var { data } = await this.$axios.put(
        `users/${this.userRolesData.id}/role`,
        { rid: this.roleId }
      );
      this.dialogFormRoles = false;
      if (data.meta.status == 200) {
        this.$message({
          type: "success",
          message: "修改成功!",
        });
        this.getusers();
      } else {
        this.$message.error(data.meta.msg);
      }
    },
  },

  async mounted() {
    this.getusers(1, 3);
  },
};
</script>

<style>
</style>